package yl.hs.bmipfull.service.material.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.material.IRawMaterialPriceDao;
import yl.hs.bmipfull.pojo.host.ProductionLineRawConfigEntity;
import yl.hs.bmipfull.pojo.material.RawMaterialInfoEntity;
import yl.hs.bmipfull.pojo.material.RawMaterialPriceEntity;
import yl.hs.bmipfull.service.host.IProductionLineRawConfigService;
import yl.hs.bmipfull.service.material.IRawMaterialInfoService;
import yl.hs.bmipfull.service.material.IRawMaterialPriceService;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.VoUtil;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;
import yl.hs.bmipfull.viewmodels.material.GenerateRawPriceVO;
import yl.hs.bmipfull.viewmodels.salemanmage.SetTimeVO;
import yl.hs.bmipfull.viewmodels.salemanmage.TimeGroupVO;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 张凯
 * @apiNote 原材耗材价格服务层接口实现
 * @since 2022年03月07日 16时18分11秒 <br/>
 */
@Service
public class RawMaterialPriceServiceImpl extends PurchaseBaseService implements IRawMaterialPriceService {

    @Autowired
    IRawMaterialPriceDao dao;

    @Autowired
    IProductionLineRawConfigService rawConfigService;

    @Autowired
    IRawMaterialInfoService materialInfoService;

    @Override
    public List<RawMaterialPriceEntity> queryList(PageQuery pageQuery) throws Exception {
        pageQuery.checkSortSides(RawMaterialPriceEntity.class);
        int year = Integer.parseInt(pageQuery.getQuery().get("priceYear").toString());
        int month = Integer.parseInt(pageQuery.getQuery().get("priceMonth").toString());
        List<RawMaterialPriceEntity> entityList = dao.queryPage(pageQuery.getQuery());
        List<ProductionLineRawConfigEntity> rawConfigList = rawConfigService.queryList(pageQuery);
        var rawPriceRmSnSet = entityList.stream().map(RawMaterialPriceEntity::getRmSn).collect(Collectors.toSet());
        var configRawSnSet = rawConfigList.stream().map(ProductionLineRawConfigEntity::getRawSn).collect(Collectors.toSet());
        if (configRawSnSet.size() > rawPriceRmSnSet.size()){
            configRawSnSet.removeAll(rawPriceRmSnSet);
            configRawSnSet.forEach(configRawSn -> {
                RawMaterialInfoEntity materialInfoEntity = materialInfoService.findBySn(configRawSn);
                if (materialInfoEntity != null){
                    RawMaterialPriceEntity priceEntity = new RawMaterialPriceEntity();
                    priceEntity.setPrice(BigDecimal.ZERO);
                    priceEntity.setRmSn(materialInfoEntity.getSn());
                    priceEntity.setPriceYear(year);
                    priceEntity.setPriceMonth(month);
                    priceEntity.setRmName(materialInfoEntity.getRmName());
                    priceEntity.setRmSpec(materialInfoEntity.getRmSpec());
                    entityList.add(priceEntity);
                }
            });
            return entityList;
        }else if (configRawSnSet.size() < rawPriceRmSnSet.size()){
            rawPriceRmSnSet.removeAll(configRawSnSet);
            configRawSnSet.forEach(configRawSn ->{
                List<RawMaterialPriceEntity> tempRawPriceList = entityList.stream().filter(t -> t.getRmSn().equals(configRawSn)).toList();
                if (tempRawPriceList!= null && tempRawPriceList.size() > 0){
                    RawMaterialPriceEntity tempPrice = tempRawPriceList.get(0);
                    delete(tempPrice.getId());
                    entityList.remove(tempPrice);
                }
            });
            return entityList;
        }else  {
            return entityList;
        }
    }

    @Override
    public PageResult<RawMaterialPriceEntity> queryPage(PageQuery pageQuery, int rowNum, int page) throws Exception {
        pageQuery.checkSortSides(RawMaterialPriceEntity.class);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        PageResult<RawMaterialPriceEntity> result = new PageResult(rowNum);
        result.setRecords(dao.queryCountByCondition(pageQuery.getQuery()));
        result.setPage(page);
        result.setData(dao.queryPage(pageQuery.getQuery()));
        return result;
    }

    @Override
    public Integer generateRawPrice(GenerateRawPriceVO generateVO) {
        PageQuery pageQuery = new PageQuery();
        Map<String,Object> query = new HashMap<String,Object>();
        query.put("priceYear", generateVO.getFromYear());
        query.put("priceMonth", generateVO.getFromMonth());
        pageQuery.setQuery(query);

        try {
            List<RawMaterialPriceEntity> rawMaterialPriceList = queryList(pageQuery);
            dao.deleteByPriceYearAndPriceMonth(generateVO.getToYear(), generateVO.getToMonth());
            rawMaterialPriceList.forEach(fromPrice ->{
                RawMaterialPriceEntity priceEntity = new RawMaterialPriceEntity();
                RawMaterialInfoEntity materialInfoEntity = materialInfoService.findBySn(fromPrice.getRmSn());
                priceEntity.setPrice(fromPrice.getPrice());
                priceEntity.setPriceYear(generateVO.getToYear());
                priceEntity.setPriceMonth(generateVO.getToMonth());
                priceEntity.setRmSn(fromPrice.getRmSn());
                if(materialInfoEntity!=null){
                    priceEntity.setRmName(materialInfoEntity.getRmName());
                    priceEntity.setRmSpec(materialInfoEntity.getRmSpec());
                    dao.insertNew(priceEntity);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
        return 1;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveRawMaterialPrice(Map<String, Object> model) throws Exception {
        Integer result;
        RawMaterialPriceEntity entity = null;
        if (model.get("id") != null){
          entity = dao.findById(Integer.parseInt(model.get("id").toString()));
        }
        if (entity == null){
            //执行保存
            entity = new RawMaterialPriceEntity();
            Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            result = dao.insertNew(entity);
            if (result > 0) {
                writeLog(ActionType.CREATE, entity.getRmSn(), "插入原材耗材价格信息", Tl.toJson(entity), RawMaterialPriceEntity.class);
            }
        } else {
            //执行修改
            Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            result = dao.update(entity);
            if (result > 0) {
                writeLog(ActionType.UPDATE, entity.getRmSn(), "更新原材耗材价格信息", Tl.toJson(entity), RawMaterialPriceEntity.class);
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer delete(Integer id) {

        return dao.deleteById(id);
    }

    @Override
    public List<TimeGroupVO> getSetTimeGroup() {
        List<SetTimeVO> setTime = dao.getSetTime();
        return VoUtil.groupTime(setTime);
    }
}